package tool;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class RegexReader {
	public static final String PatternNodeName = "pattern";
	public static final String PatternAttrDescName = "desc";
	public static final String PatternAttrExprName = "expr";
	public static final String PatternAttrCountName = "count";
	public static final String PatternAttrArg0Name = "arg0";
	public static final String PatternAttrArg1Name = "arg1";
	public static final String MatchNodeName = "match";
	public static final String MatchAttrTextName = "text";
	public static final String MatchAttrDocName = "doc";
	public static final String MatchAttrOffsetName = "offset";
	private Element root = null;
	private Document document = null;

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

	public void readRegex(String regex_file) throws Exception {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = factory.newDocumentBuilder();
		File file = new File(regex_file);
		document = builder.parse(file);
		root = document.getDocumentElement();
	}

	public void saveXml(String filename) throws FileNotFoundException,
			TransformerException {
		if (document == null)
			return;
		TransformerFactory tf = TransformerFactory.newInstance();
		Transformer transformer = tf.newTransformer();
		DOMSource source = new DOMSource(document);
		transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
		transformer.setOutputProperty(OutputKeys.INDENT, "yes");
		transformer.setOutputProperty(
				"{http://xml.apache.org/xslt}indent-amount", "4");// tricky
		PrintWriter pw = new PrintWriter(new FileOutputStream(filename));
		StreamResult result = new StreamResult(pw);
		transformer.transform(source, result);
		pw.close();
	}

	public Element getRoot() {
		return root;
	}

	public Document getDocument() {
		return document;
	}

}
